package com.yuns.model.service.impl;
import com.yuns.model.entity.SysDict;
import com.yuns.model.mapper.SysDictMapper;
import com.yuns.model.service.SysDictService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author luwenchao
 * @since 2019-11-14
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {
    @Override
    public List<SysDict> selectDictList() {
        List<SysDict> sysDicts = baseMapper.selectList(null);
        List<SysDict> sysDictsList = new ArrayList<>();
        sysDicts.stream().forEach(x -> {
                    if (x.getPid() == 0) {
                        sysDictsList.add(x);
                    }
                }
        );
        findChildren(sysDictsList, sysDicts);
        return sysDictsList;
    }
    /*
     *根据字典编码查询一级字典
     */
    @Override
    public List<SysDict> selectListByCode(String code) {
        return baseMapper.selectListByCode(code);
    }

    private void findChildren(List<SysDict> sysDictsList, List<SysDict> sysDicts) {
        for (SysDict sysDict : sysDictsList) {
            List<SysDict> children = new ArrayList<>();
            for (SysDict sysDict1 : sysDicts) {
                if (sysDict.getId() != null && sysDict.getId().equals(sysDict1.getPid())) {
                    sysDict.setParentName(sysDict.getName());
                    children.add(sysDict1);
                }
            }
            sysDict.setChildren(children);
            findChildren(children, sysDicts);
        }
    }
}
